package session

import (
	"time"
	"io"
	"strconv"
	"encoding/base64"
	"crypto/rand"
)

/*会话*/
type sessionBean struct {
	SessionID        string                 `json:"session_id"`         //唯一id
	UserID           string                 `json:"user_id"`            //用户id
	LastTimeAccessed time.Time              `json:"last_time_accessed"` //最后访问时间
	Values           map[string]interface{} `json:"values"`             //其它对应值(保存用户所对应的一些值，比如用户权限之类)
	MaxLifeTime      int64                  `json:"max_life_time"`      //垃圾回收时间
}

func newSession(userId string) *sessionBean {
	return &sessionBean{
		UserID:           userId,
		SessionID:        createSessionID(),
		LastTimeAccessed: time.Now(),
		Values:           make(map[string]interface{}),
	}
}

func (session *sessionBean) SetValue(key string, v interface{}) {
	session.Values[key] = v
}
func (session *sessionBean) UpLastTimeAccessed() (*sessionBean) {
	session.LastTimeAccessed = time.Now()
	return session
}
func (session *sessionBean) GetValue(key string) (interface{}, bool) {
	v, ok := session.Values[key]
	return v, ok
}

//是否过期
func (session *sessionBean) IsExpire() bool {
	if session.MaxLifeTime < 0 {
		return false
	}
	if session.LastTimeAccessed.Unix()+session.MaxLifeTime < time.Now().Unix() {
		return true
	}
	return false
}
func (session *sessionBean) DeleteValue(keys ...string) {
	for _, v := range keys {
		delete(session.Values, v)
	}

}

//创建唯一ID
func createSessionID() string {
	b := make([]byte, 32)
	if _, err := io.ReadFull(rand.Reader, b); err != nil {
		nano := time.Now().UnixNano() //微秒
		return strconv.FormatInt(nano, 10)
	}
	return base64.URLEncoding.EncodeToString(b)
}
